package com.example.fanyi.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.fanyi.api.YoudaoApi
import com.example.fanyi.api.YoudaoUtils
import com.example.fanyi.data.TranslationDatabase
import com.example.fanyi.data.TranslationRecord
import com.example.fanyi.data.TranslationRepository
import com.example.fanyi.data.TranslationResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class TranslationViewModel(application: Application) : AndroidViewModel(application) {
    private val database = TranslationDatabase.getDatabase(application)
    private val translationDao = database.translationDao()
    private val repository = TranslationRepository(application)

    // API服务
    private val youdaoApi: YoudaoApi by lazy {
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        val client = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .build()

        Retrofit.Builder()
            .baseUrl("https://openapi.youdao.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(YoudaoApi::class.java)
    }

    // UI状态
    private val _sourceText = MutableStateFlow("")
    val sourceText = _sourceText.asStateFlow()

    private val _translatedText = MutableStateFlow("")
    val translatedText = _translatedText.asStateFlow()

    private val _isChineseToUyghur = MutableStateFlow(true)
    val isChineseToUyghur = _isChineseToUyghur.asStateFlow()

    private val _translationRecords = MutableStateFlow<List<TranslationRecord>>(emptyList())
    val translationRecords = _translationRecords.asStateFlow()

    // 添加错误状态
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage = _errorMessage.asStateFlow()

    init {
        // 加载翻译记录
        viewModelScope.launch {
            repository.getAllRecords().collect { records ->
                _translationRecords.value = records
            }
        }
    }

    // 更新源文本
    fun updateSourceText(text: String) {
        _sourceText.value = text
        // 清除之前的错误信息
        _errorMessage.value = null
    }

    // 切换翻译方向
    fun toggleTranslationDirection() {
        _isChineseToUyghur.value = !_isChineseToUyghur.value
    }

    // 执行翻译
    fun translate() {
        viewModelScope.launch {
            try {
                _errorMessage.value = null
                val sourceText = _sourceText.value.trim()
                if (sourceText.isEmpty()) {
                    _errorMessage.value = "请输入要翻译的文本"
                    return@launch
                }

                // 分段翻译，每段最多1000字
                val segments = sourceText.chunked(1000)
                val translatedSegments = mutableListOf<String>()

                for (segment in segments) {
                    val result = repository.translate(
                        text = segment,
                        isChineseToUyghur = _isChineseToUyghur.value
                    )

                    when (result) {
                        is TranslationResult.Success -> {
                            translatedSegments.add(result.translatedText)
                        }
                        is TranslationResult.Error -> {
                            when (result.code) {
                                202 -> _errorMessage.value = "翻译错误：请检查输入的文本是否包含不支持的字符"
                                401 -> _errorMessage.value = "翻译错误：未授权，请检查API密钥"
                                402 -> _errorMessage.value = "翻译错误：API余额不足"
                                else -> _errorMessage.value = "翻译错误：${result.code}"
                            }
                            return@launch
                        }
                    }
                }

                // 合并所有翻译结果
                val finalTranslation = translatedSegments.joinToString("\n")
                _translatedText.value = finalTranslation

                // 保存翻译记录
                repository.insertRecord(
                    TranslationRecord(
                        sourceText = sourceText,
                        translatedText = finalTranslation,
                        isChineseToUyghur = _isChineseToUyghur.value,
                        timestamp = System.currentTimeMillis()
                    )
                )
            } catch (e: Exception) {
                _errorMessage.value = "翻译出错：${e.message}"
            }
        }
    }

    // 删除翻译记录
    fun deleteRecord(record: TranslationRecord) {
        viewModelScope.launch {
            translationDao.delete(record)
        }
    }

    // 删除多个翻译记录
    fun deleteRecords(records: Set<TranslationRecord>) {
        viewModelScope.launch {
            repository.deleteRecords(records)
        }
    }
} 